package com.ztgf.file.utils;

import com.ztgf.common.utils.FileUtils;
import com.ztgf.common.utils.ImageUtils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description:
 * @Author: mxli
 * @Date: 2021-01-20 16:21
 **/
public class TextWatermarking {

    public static void main(String[] args) {
        String iconPath="C:/Users/solexit06/Desktop/temp/logo.png";//作为水印的图片
        String targerPath1 = "C:/Users/solexit06/Desktop/sj01.png";//添加水印后保持路径
//        String srcImgPath = "/Users/mxli/Desktop/dhh1dWAJk5iAaVjrAA3VcscEnCQ58.jpeg";//需要加水印的源图片
        String srcImgPath = "/Users/mxli/Desktop/dhh1dWAJk5iAaVjrAA3VcscEnCQ58.jpeg";//需要加水印的源图片
        String targerPath2 = "/Users/mxli/Desktop/dhh1dWAJk5iAaVjrAA3VcscEnCQ58wm.jpg";//添加水印后保持路径

        Date date= Calendar.getInstance().getTime();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String dateStr=sdf.format(date);

//        TextWatermarking.markImageByIcon(iconPath, srcImgPath, targerPath1); // 给图片添加水印
        TextWatermarking.waterMarkByText(dateStr, srcImgPath, targerPath2, 0, 180, 133, 0.2f);//给图片添加文字水印
    }

    /**
     * 给图片添加“图片水印”
     * @param iconPath 作为水印的图片路径
     * @param srcImgPath 源图片路径
     * @param targerPath 目标图片路径
     */
    public static void markImageByIcon(String iconPath, String srcImgPath,String targerPath) {
        markImageByIcon(iconPath, srcImgPath, targerPath, null);
    }

    /**
     * 给图片添加“图片水印”、可设置图片水印旋转角度
     * @param iconPath 作为水印的图片路径
     * @param srcImgPath 源图片路径
     * @param targerPath 目标图片路径
     * @param degree 水印图片旋转角度
     */
    public static void markImageByIcon(String iconPath, String srcImgPath,String targerPath, Integer degree) {
        OutputStream os = null;
        try {
            //1、源图片
            Image srcImg = ImageIO.read(new File(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);

            //2、水印图象：水印一般为gif或者png的，这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(iconPath);
            Image img = imgIcon.getImage();// 得到Image对象。

            //3、画笔对象
            Graphics2D g2d = buffImg.createGraphics();
            // ----------  增加下面的代码使得背景透明  -----------------
            buffImg = g2d.getDeviceConfiguration().createCompatibleImage(
                    srcImg.getWidth(null),srcImg.getHeight(null),Transparency.TRANSLUCENT);
            g2d.dispose();
            g2d = buffImg.createGraphics();
            // ----------  背景透明代码结束  -----------------

            // 设置对线段的锯齿状边缘处理
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);// 设置对线段的锯齿状边缘处理

            g2d.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),
                    srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

            // 设置水印旋转
            if (null != degree) {
                g2d.rotate(Math.toRadians(degree),(double) buffImg.getWidth()/2,
                        (double) buffImg.getHeight()/2);
            }

            // 透明度
            float alpha = 1.0f;
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

            // 表示水印图片的位置
            g2d.drawImage(img, 90, 92, null);

            //4、释放资源
            g2d.dispose();

            //5、生成图片
            os = new FileOutputStream(targerPath);
            ImageIO.write(buffImg,"PNG",os);

//            System.out.println("图片完成添加Icon印章");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给图片添加“文字水印”、可设置旋转角度
     * @param logoText 水印文字
     * @param srcImgPath 源图片路径
     * @param targerPath 目标图片路径
     * @param degree 水印图片旋转角度
     * @param width 宽度(与左相比)
     * @param height 高度(与顶相比)
     * @param clarity 透明度(小于1的数)越接近0越透明
     */
    public static void waterMarkByText(String logoText, String srcImgPath,
                                       String targerPath, Integer degree, Integer width, Integer height,
                                       Float clarity) {

        InputStream is = null;
        OutputStream os = null;
        try {
            /**1、源图片*/
            Image srcImg = ImageIO.read(new File(srcImgPath));
            //创建BufferedImage对象:new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
            //其实就是以源图片的宽度为宽，以源图片的长度为长
            int srcWidth = srcImg.getWidth(null);
            int srcHeight = srcImg.getHeight(null);
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);

            /**2、得到画笔对象*/
            Graphics2D g2d = buffImg.createGraphics();

            // ----------  增加下面的代码使得背景透明  -----------------
            buffImg = g2d.getDeviceConfiguration().createCompatibleImage(srcImg.getWidth(null),srcImg.getHeight(null),Transparency.TRANSLUCENT);
            g2d.dispose();
            g2d = buffImg.createGraphics();
            // ----------  背景透明代码结束  -----------------

            // 设置对线段的锯齿状边缘处理
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            //把源图片写入
            g2d.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0,null);

            // 设置水印旋转
            if (null != degree) {
                degree = -45;
                g2d.rotate(Math.toRadians(degree),(double) buffImg.getWidth() / 2,(double) buffImg.getHeight() / 2);
            }

            // 设置颜色
            g2d.setColor(Color.red);

            Font font = new Font("微软雅黑", Font.ROMAN_BASELINE, 33);
            // 设置 Font
            g2d.setFont(font);

            //设置透明度:1.0f为透明度 ，值从0-1.0，依次变得不透明
            float alpha = clarity;
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));
//            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));//透明度设置 结束
            //文字内容，文字在图片上的坐标位置(x,y)
//            g2d.drawString(logoText, width, height);

            //获取文字所占的像素
            FontRenderContext context = g2d.getFontRenderContext();
            Rectangle2D stringBounds = font.getStringBounds(logoText,context);
            int textWidth = (int) stringBounds.getWidth() ;
            int textHeight = (int) stringBounds.getHeight();

            int markWidth = 33 * getTextLength (logoText);// 字体长度
            int markHeight = 33;// 字体高度

            srcWidth = srcHeight;

            int x = -srcWidth / 2;
            int y = 0;

            // 循环添加水印
            while (x < srcWidth) {
                y = -srcHeight / 2;
                while (y < srcHeight) {
                    g2d.drawString (logoText, x, y);

                    y += textHeight + 100;
                }
                x += textWidth + 100;
            }
            //释放资源
            g2d .dispose();

            /**3、生成图片*/
            os = new FileOutputStream(targerPath);
            ImageIO.write(buffImg, "png", os);

//            byte[] bytes = FileUtils.image2byte(buffImg, "jpg");
//            ImageIO.write(ImageUtils.toImage(bytes), "png", new File("/Users/mxli/Desktop/targer_mark.jpeg"));

//            System.out.println("添加水印文字完成!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文本长度。汉字为1:1，英文和数字为2:1
     */
    private static int getTextLength (String text) {
        int length = text.length ();
        for (int i = 0; i < text.length (); i++) {
            String s = String.valueOf (text.charAt (i));
            if (s.getBytes ().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }
}
